<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2021/7/5
 * Time: 9:31 下午
 */
namespace app\lib;

use app\lib\exception\BaseException;
use think\exception\Handle;
use think\exception\HttpResponseException;
use think\facade\Env;
use think\Request;
use think\Response;
use \Throwable;

class ExceptionHandler extends Handle
{

    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [

    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report (Throwable $exception): void {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render ($request, Throwable $e): Response {
        $debug = Env::get('app_debug');
        if ($e instanceof BaseException) {
            $code = $e->code;
            $msg = $e->msg;
            $errorCode = $e->errorCode;
            if (empty($msg)) {
                $msg = ErrorCode::getErrorMsg($errorCode);
            }
            $data = $e->data;
        } else {
            if ($debug || $e instanceof HttpResponseException) {
                return parent::render($request, $e);
            }
            $code = 500;
            $msg = '服务器异常';
            $errorCode = 50000;
            $data = null;
        }
        $result = [
            'code' => $errorCode,
            'msg'  => $msg,
            'data' => $data
        ];
        return Response::create($result, 'json', $code);
    }
}
